<template>
  <div>
    <el-card class="box-card">
      <h2>修改密码</h2>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-position="left" label-width="80px"
        class="demo-ruleForm">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name" :disabled="true" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="旧密码" prop="oldPassword">
          <el-input type="password" v-model="ruleForm.oldPassword" autocomplete="off" placeholder="请输入旧密码"
            :disabled="loading"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="ruleForm.newPassword" autocomplete="off" placeholder="请输入新密码"
            :disabled="loading"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="ruleForm.confirmPassword" autocomplete="off" placeholder="请再次输入确认密码"
            :disabled="loading"></el-input>
        </el-form-item>
      </el-form>
      <div class="btnGroup">
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading" :disabled="loading">
          {{ loading ? '验证中...' : '提交' }}
        </el-button>
        <el-button @click="goBack" :disabled="loading">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'ChangePassword',
  data() {
    // 验证确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    // 验证新密码不能与旧密码相同
    const validateNewPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else if (value === this.ruleForm.oldPassword) {
        callback(new Error('新密码不能与旧密码相同'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      ruleForm: {
        name: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
      rules: {
        name: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { validator: validateNewPassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
      },
    }
  },
  mounted() {
    // 从sessionStorage获取用户信息
    const user = sessionStorage.getItem("user");
    if (user) {
      const userData = JSON.parse(user);
      this.ruleForm.name = userData.name;
    } else {
      // 如果没有用户信息，跳转到登录页
      this.$router.push("/login");
    }
  },
  methods: {
    // 验证旧密码是否正确
    async validateOldPassword(name, oldPassword) {
      try {
        console.log('验证旧密码，发送数据:', { name, oldPassword });

        const response = await axios.post('/api/user/login', null, {
          params: {
            name: name,
            password: oldPassword
          }
        });

        console.log('旧密码验证响应:', response.data);

        // 如果登录成功，说明旧密码正确
        return response.data.code === '0';
      } catch (error) {
        console.log('旧密码验证失败:', error.response?.data || error.message);
        // 登录失败，说明旧密码错误
        return false;
      }
    },

    // 提交表单
    async submitForm(formName) {
      try {
        // 验证表单
        const valid = await this.$refs[formName].validate();
        if (!valid) {
          return false;
        }

        this.loading = true;

        // 先验证旧密码是否正确
        const isOldPasswordCorrect = await this.validateOldPassword(
          this.ruleForm.name,
          this.ruleForm.oldPassword
        );

        if (!isOldPasswordCorrect) {
          ElMessage.error('旧密码不正确，请重新输入');
          this.loading = false;
          return;
        }

        // 旧密码验证通过，准备发送修改密码请求
        const changePasswordData = {
          name: this.ruleForm.name,
          oldPassword: this.ruleForm.oldPassword,
          newPassword: this.ruleForm.newPassword
        };

        console.log('发送给后端的数据:', changePasswordData);

        // 调用修改密码API
        try {
          await axios.post('/api/user/change-password', null, {
            params: changePasswordData
          });
          ElMessage.success('密码修改成功！');

          // 清空表单
          this.ruleForm.oldPassword = '';
          this.ruleForm.newPassword = '';
          this.ruleForm.confirmPassword = '';

          // 跳转到home页面
          this.$router.push('/home');
        } catch (error) {
          ElMessage.error(error.response?.data?.message || '修改密码失败，请稍后重试');
        }
      } finally {
        this.loading = false;
      }
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1);
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: auto auto;
  width: 400px;
}

.btnGroup {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.btnGroup .el-button {
  min-width: 80px;
}
</style>